/**
 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "plugins/ecmascript/runtime/base/builtins_base.h"

#include "plugins/ecmascript/runtime/base/number_helper.h"
#include "plugins/ecmascript/runtime/ecma_macros.h"
#include "plugins/ecmascript/runtime/global_env.h"
#include "plugins/ecmascript/runtime/js_handle.h"
#include "plugins/ecmascript/runtime/js_hclass.h"
#include "plugins/ecmascript/runtime/js_number_format.h"
#include "plugins/ecmascript/runtime/js_primitive_ref.h"
#include "plugins/ecmascript/runtime/js_tagged_number.h"
#include "plugins/ecmascript/runtime/js_tagged_value-inl.h"
#include "plugins/ecmascript/runtime/object_factory.h"
#include "plugins/ecmascript/runtime/tagged_hash_table.h"

namespace ark::ecmascript::builtins {
using NumberHelper = ecmascript::base::NumberHelper;

// 18.2.4
// 20.1.2.12
static JSTaggedValue ParseFloatStr(const Span<const uint8_t> &str);
// 18.2.5
// 20.1.2.13
static JSTaggedValue ParseIntStr(const Span<const uint8_t> &str, int32_t radix);
static JSTaggedNumber ThisNumberValue(EcmaRuntimeCallInfo *argv);

// 20.1.1.1
JSTaggedValue number::NumberConstructor(EcmaRuntimeCallInfo *argv)
{
    ASSERT(argv);
    BUILTINS_API_TRACE(argv->GetThread(), Number, NumberConstructor);
    JSThread *thread = argv->GetThread();
    [[maybe_unused]] EcmaHandleScope handleScope(thread);
    JSHandle<JSTaggedValue> newTarget = builtins_common::GetNewTarget(argv);
    // 1. If no arguments were passed to this function invocation, let n be +0.
    JSTaggedNumber numberValue(0);
    if (argv->GetArgsNumber() > 0) {
        // 2. Else, let n be ToNumber(value).
        JSHandle<JSTaggedValue> numberInput = builtins_common::GetCallArg(argv, 0);
        numberValue = JSTaggedValue::ToNumber(thread, numberInput);
        RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
    }
    // 4. If NewTarget is undefined, return n.
    if (newTarget->IsUndefined()) {
        return numberValue;
    }
    // 5. Let O be OrdinaryCreateFromConstructor(NewTarget, "%NumberPrototype%", «[[NumberData]]» ).
    JSHandle<JSTaggedValue> constructor = builtins_common::GetConstructor(argv);
    JSHandle<JSObject> result =
        thread->GetEcmaVM()->GetFactory()->NewJSObjectByConstructor(JSHandle<JSFunction>::Cast(constructor), newTarget);
    // 6. ReturnIfAbrupt(O).
    RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
    // 7. Set the value of O’s [[NumberData]] internal slot to n.
    JSPrimitiveRef::Cast(*result)->SetValue(thread, numberValue);
    // 8. Return O.
    return result.GetTaggedValue();
}

// 20.1.2.2
JSTaggedValue number::IsFinite(EcmaRuntimeCallInfo *argv)
{
    ASSERT(argv);
    BUILTINS_API_TRACE(argv->GetThread(), Number, IsFinite);
    JSTaggedValue msg = builtins_common::GetCallArg(argv, 0).GetTaggedValue();
    // 1. If Type(number) is not Number, return false
    // 2. If number is NaN, +infinite, or -infinite, return false
    if (NumberHelper::IsFinite(msg)) {
        return builtins_common::GetTaggedBoolean(true);
    }
    return builtins_common::GetTaggedBoolean(false);
}

// 20.1.2.3
JSTaggedValue number::IsInteger(EcmaRuntimeCallInfo *argv)
{
    ASSERT(argv);
    BUILTINS_API_TRACE(argv->GetThread(), Number, IsInteger);
    JSThread *thread = argv->GetThread();
    JSHandle<JSTaggedValue> msg = builtins_common::GetCallArg(argv, 0);
    bool result = false;
    // 1. If Type(number) is not Number, return false.
    // 2. If number is NaN, +infinite, or -infinite, return false
    if (NumberHelper::IsFinite(msg.GetTaggedValue())) {
        [[maybe_unused]] EcmaHandleScope handleScope(thread);
        double value = JSTaggedNumber(msg.GetTaggedValue()).GetNumber();
        // 3. Let integer be ToInteger(number).
        JSTaggedNumber number = JSTaggedValue::ToInteger(thread, msg);
        // 4. If integer is not equal to number, return false.
        // 5. Otherwise, return true.
        result = (value == number.GetNumber());
    }
    return builtins_common::GetTaggedBoolean(result);
}

// 20.1.2.4
JSTaggedValue number::IsNaN(EcmaRuntimeCallInfo *argv)
{
    ASSERT(argv);
    BUILTINS_API_TRACE(argv->GetThread(), Number, IsNaN);
    JSTaggedValue msg = builtins_common::GetCallArg(argv, 0).GetTaggedValue();
    // 1. If Type(number) is not Number, return false.
    // 2. If number is NaN, return true.
    if (NumberHelper::IsNaN(msg)) {
        return builtins_common::GetTaggedBoolean(true);
    }
    // 3. Otherwise, return false.
    return builtins_common::GetTaggedBoolean(false);
}

// 20.1.2.5
JSTaggedValue number::IsSafeInteger(EcmaRuntimeCallInfo *argv)
{
    ASSERT(argv);
    BUILTINS_API_TRACE(argv->GetThread(), Number, IsSafeInteger);
    JSThread *thread = argv->GetThread();
    JSHandle<JSTaggedValue> msg = builtins_common::GetCallArg(argv, 0);
    bool result = false;
    // 1. If Type(number) is not Number, return false.
    // 2. If number is NaN, +infinite, or -infinite, return false
    if (NumberHelper::IsFinite(msg.GetTaggedValue())) {
        [[maybe_unused]] EcmaHandleScope handleScope(thread);
        double value = JSTaggedNumber(msg.GetTaggedValue()).GetNumber();
        // 3. Let integer be ToInteger(number).
        JSTaggedNumber number = JSTaggedValue::ToInteger(thread, msg);
        // 4. If integer is not equal to number, return false.
        // 5. If abs(integer) ≤ 253−1, return true.
        result = (value == number.GetNumber()) && std::abs(value) <= ecmascript::base::MAX_SAFE_INTEGER;
    }
    return builtins_common::GetTaggedBoolean(result);
}

// 18.2.4
// 20.1.2.12
JSTaggedValue ParseFloatStr(const Span<const uint8_t> &str)
{
    // 4. If neither trimmedString nor any prefix of trimmedString satisfies the syntax of a StrDecimalLiteral
    // (see 7.1.3.1), return NaN.
    if (NumberHelper::IsEmptyString(str.begin(), str.end())) {
        return builtins_common::GetTaggedDouble(base::NAN_VALUE);
    }
    double result = NumberHelper::StringToDouble(str.begin(), str.end(), 0, base::IGNORE_TRAILING);
    return builtins_common::GetTaggedDouble(result);
}

JSTaggedValue builtins::number::ParseFloat(EcmaRuntimeCallInfo *argv)
{
    ASSERT(argv);
    BUILTINS_API_TRACE(argv->GetThread(), Number, ParseFloat);
    JSThread *thread = argv->GetThread();
    JSHandle<JSTaggedValue> msg = builtins_common::GetCallArg(argv, 0);
    if (msg->IsUndefined()) {
        return builtins_common::GetTaggedDouble(ecmascript::base::NAN_VALUE);
    }
    [[maybe_unused]] EcmaHandleScope handleScope(thread);
    // 1. Let inputString be ToString(string).
    JSHandle<EcmaString> numberString = JSTaggedValue::ToString(thread, msg);
    // 2. ReturnIfAbrupt(inputString).
    RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);

    if (UNLIKELY(numberString->IsUtf16())) {
        size_t len = utf::Utf16ToUtf8Size(numberString->GetDataUtf16(), numberString->GetLength()) - 1;
        PandaVector<uint8_t> buf(len);
        len =
            utf::ConvertRegionUtf16ToUtf8(numberString->GetDataUtf16(), buf.data(), numberString->GetLength(), len, 0);
        auto str = Span<const uint8_t>(buf.data(), len);
        return ParseFloatStr(str);
    }

    auto str = Span<const uint8_t>(numberString->GetDataUtf8(), numberString->GetUtf8Length() - 1);
    return ParseFloatStr(str);
}

// 18.2.5
// 20.1.2.13
JSTaggedValue ParseIntStr(const Span<const uint8_t> &str, int32_t radix)
{
    return NumberHelper::StringToDoubleWithRadix(str.begin(), str.end(), radix);
}

JSTaggedValue builtins::number::ParseInt(EcmaRuntimeCallInfo *argv)
{
    ASSERT(argv);
    BUILTINS_API_TRACE(argv->GetThread(), Number, ParseInt);
    JSThread *thread = argv->GetThread();
    [[maybe_unused]] EcmaHandleScope handleScope(thread);
    JSHandle<JSTaggedValue> msg = builtins_common::GetCallArg(argv, 0);
    JSHandle<JSTaggedValue> arg2 = builtins_common::GetCallArg(argv, 1);
    int32_t radix = 0;

    if (!arg2->IsUndefined()) {
        // 7. Let R = ToInt32(radix).
        radix = JSTaggedValue::ToInt32(thread, arg2);
        RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
    }
    // 1. Let inputString be ToString(string).
    JSHandle<EcmaString> numberString = JSTaggedValue::ToString(thread, msg);
    RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);

    if (UNLIKELY(numberString->IsUtf16())) {
        size_t len = utf::Utf16ToUtf8Size(numberString->GetDataUtf16(), numberString->GetLength()) - 1;
        PandaVector<uint8_t> buf(len);
        len =
            utf::ConvertRegionUtf16ToUtf8(numberString->GetDataUtf16(), buf.data(), numberString->GetLength(), len, 0);
        auto str = Span<const uint8_t>(buf.data(), len);
        return ParseIntStr(str, radix);
    }

    auto str = Span<const uint8_t>(numberString->GetDataUtf8(), numberString->GetUtf8Length() - 1);
    return ParseIntStr(str, radix);
}

// prototype
// 20.1.3.2
JSTaggedValue number::proto::ToExponential(EcmaRuntimeCallInfo *argv)
{
    ASSERT(argv);
    BUILTINS_API_TRACE(argv->GetThread(), NumberPrototype, ToExponential);
    JSThread *thread = argv->GetThread();
    [[maybe_unused]] EcmaHandleScope handleScope(thread);
    // 1. Let x be ? thisNumberValue(this value).
    JSTaggedNumber value = ThisNumberValue(argv);
    // 2. ReturnIfAbrupt(x).
    RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);

    // 3. Let f be ToInteger(fractionDigits).
    JSHandle<JSTaggedValue> digits = builtins_common::GetCallArg(argv, 0);
    JSTaggedNumber digitInt = JSTaggedValue::ToInteger(thread, digits);
    // 5. ReturnIfAbrupt(f).
    RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);

    double values = value.GetNumber();
    // 6. If x is NaN, return the String "NaN".
    if (std::isnan(values)) {
        return builtins_common::GetTaggedString(thread, "NaN");
    }
    // 8. If x < 0, then
    //    a. Let s be "-".
    //    b. Let x = –x.
    // 9. If x = +infinity, then
    //    a. Return the concatenation of the Strings s and "Infinity".
    if (!std::isfinite(values)) {
        if (values < 0) {
            return builtins_common::GetTaggedString(thread, "-Infinity");
        }
        return builtins_common::GetTaggedString(thread, "Infinity");
    }

    // 4. Assert: f is 0, when fractionDigits is undefined.
    // 10. If f < 0 or f > 20, throw a RangeError exception
    double fraction = digitInt.GetNumber();
    if (digits->IsUndefined()) {
        fraction = -1;
    } else {
        if (fraction < ecmascript::base::MIN_FRACTION || fraction > ecmascript::base::MAX_FRACTION) {
            THROW_RANGE_ERROR_AND_RETURN(thread, "fraction must be 0 to 100", JSTaggedValue::Exception());
        }
    }
    return NumberHelper::DoubleToExponential(thread, values, static_cast<int>(fraction));
}

// 20.1.3.3
JSTaggedValue number::proto::ToFixed(EcmaRuntimeCallInfo *argv)
{
    ASSERT(argv);
    BUILTINS_API_TRACE(argv->GetThread(), NumberPrototype, ToFixed);
    JSThread *thread = argv->GetThread();
    [[maybe_unused]] EcmaHandleScope handleScope(thread);
    // 1. Let x be ? thisNumberValue(this value).
    JSTaggedNumber value = ThisNumberValue(argv);
    // 2. ReturnIfAbrupt(x).
    RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
    // 3. Let f be ToInteger(fractionDigits). (If fractionDigits is undefined, this step produces the value 0).
    JSHandle<JSTaggedValue> digitArgv = builtins_common::GetCallArg(argv, 0);
    JSTaggedNumber digitInt = JSTaggedValue::ToInteger(thread, digitArgv);
    if (digitArgv->IsUndefined()) {
        digitInt = JSTaggedNumber(0);
    }
    // 4. ReturnIfAbrupt(f).
    RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);

    double digit = digitInt.GetNumber();
    if (digit < ecmascript::base::MIN_FRACTION || digit > ecmascript::base::MAX_FRACTION) {
        THROW_RANGE_ERROR_AND_RETURN(thread, "fraction must be 0 to 100", JSTaggedValue::Exception());
    }

    // 6. If x is NaN, return the String "NaN".
    double valueNumber = value.GetNumber();
    if (std::isnan(valueNumber)) {
        return builtins_common::GetTaggedString(thread, "NaN");
    }
    // 9. If x  1021, then
    //    a. Let m = ToString(x).
    const double firstNoFixed = 1e21;
    if (valueNumber >= firstNoFixed) {
        return value.ToString(thread).GetTaggedValue();
    }

    return NumberHelper::DoubleToFixed(thread, valueNumber, static_cast<int>(digit));
}

// 20.1.3.4
JSTaggedValue number::proto::ToLocaleString(EcmaRuntimeCallInfo *argv)
{
    ASSERT(argv);
    JSThread *thread = argv->GetThread();
    BUILTINS_API_TRACE(thread, NumberPrototype, ToLocaleString);
    [[maybe_unused]] EcmaHandleScope handleScope(thread);
    // 1. Let x be ? thisNumberValue(this value).
    JSTaggedNumber x = ThisNumberValue(argv);
    RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
    // 2. Let numberFormat be ? Construct(%NumberFormat%, « locales, options »).
    JSHandle<JSTaggedValue> ctor = thread->GetEcmaVM()->GetGlobalEnv()->GetNumberFormatFunction();
    ObjectFactory *factory = thread->GetEcmaVM()->GetFactory();
    JSHandle<JSObject> obj = factory->NewJSObjectByConstructor(JSHandle<JSFunction>(ctor), ctor);
    JSHandle<JSNumberFormat> numberFormat = JSHandle<JSNumberFormat>::Cast(obj);
    JSHandle<JSTaggedValue> locales = builtins_common::GetCallArg(argv, 0);
    JSHandle<JSTaggedValue> options = builtins_common::GetCallArg(argv, 1);
    JSNumberFormat::InitializeNumberFormat(thread, numberFormat, locales, options);
    RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);

    // Return ? FormatNumeric(numberFormat, x).
    JSHandle<JSTaggedValue> result = JSNumberFormat::FormatNumeric(thread, numberFormat, x);
    RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
    return result.GetTaggedValue();
}

// 20.1.3.5
JSTaggedValue number::proto::ToPrecision(EcmaRuntimeCallInfo *argv)
{
    ASSERT(argv);
    BUILTINS_API_TRACE(argv->GetThread(), NumberPrototype, ToPrecision);
    JSThread *thread = argv->GetThread();
    [[maybe_unused]] EcmaHandleScope handleScope(thread);
    // 1. Let x be ? thisNumberValue(this value).
    JSTaggedNumber value = ThisNumberValue(argv);
    // 2. ReturnIfAbrupt(x).
    RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);

    // 3. If precision is undefined, return ToString(x).
    JSHandle<JSTaggedValue> digitArgv = builtins_common::GetCallArg(argv, 0);
    if (digitArgv->IsUndefined()) {
        return value.ToString(thread).GetTaggedValue();
    }
    // 4. Let p be ToInteger(precision).
    JSTaggedNumber digitInt = JSTaggedValue::ToInteger(thread, digitArgv);
    // 5. ReturnIfAbrupt(p).
    RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);

    // 6. If x is NaN, return the String "NaN".
    double valueNumber = value.GetNumber();
    if (std::isnan(valueNumber)) {
        return builtins_common::GetTaggedString(thread, "NaN");
    }
    // 9. If x = +infinity, then
    //    a. Return the String that is the concatenation of s and "Infinity".
    if (!std::isfinite(valueNumber)) {
        if (valueNumber < 0) {
            return builtins_common::GetTaggedString(thread, "-Infinity");
        }
        return builtins_common::GetTaggedString(thread, "Infinity");
    }

    // If p < 1 or p > 21, throw a RangeError exception
    double digit = digitInt.GetNumber();
    if (digit < ecmascript::base::MIN_FRACTION + 1 || digit > ecmascript::base::MAX_FRACTION) {
        THROW_RANGE_ERROR_AND_RETURN(thread, "fraction must be 1 to 100", JSTaggedValue::Exception());
    }
    return NumberHelper::DoubleToPrecision(thread, valueNumber, static_cast<int>(digit));
}

// 20.1.3.6
JSTaggedValue number::proto::ToString(EcmaRuntimeCallInfo *argv)
{
    ASSERT(argv);
    BUILTINS_API_TRACE(argv->GetThread(), NumberPrototype, ToString);
    JSThread *thread = argv->GetThread();
    [[maybe_unused]] EcmaHandleScope handleScope(thread);
    // 1. Let x be ? thisNumberValue(this value).
    JSTaggedNumber value = ThisNumberValue(argv);
    // 2. ReturnIfAbrupt(x).
    RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);

    // 3. If radix is not present, let radixNumber be 10.
    // 4. Else if radix is undefined, let radixNumber be 10.
    double radix = ecmascript::base::DECIMAL;
    JSHandle<JSTaggedValue> radixValue = builtins_common::GetCallArg(argv, 0);
    // 5. Else let radixNumber be ToInteger(radix).
    if (!radixValue->IsUndefined()) {
        JSTaggedNumber radixNumber = JSTaggedValue::ToInteger(thread, radixValue);
        // 6. ReturnIfAbrupt(x).
        RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
        radix = radixNumber.GetNumber();
    }

    // 7. If radixNumber < 2 or radixNumber > 36, throw a RangeError exception.
    if (radix < ecmascript::base::MIN_RADIX || radix > ecmascript::base::MAX_RADIX) {
        THROW_RANGE_ERROR_AND_RETURN(thread, "radix must be 2 to 36", JSTaggedValue::Exception());
    }
    // 8. If radixNumber = 10, return ToString(x).
    if (radix == ecmascript::base::DECIMAL) {
        return value.ToString(thread).GetTaggedValue();
    }

    double valueNumber = value.GetNumber();
    // If x is NaN, return the String "NaN".
    if (std::isnan(valueNumber)) {
        return builtins_common::GetTaggedString(thread, "NaN");
    }
    //  If x = +infinity, then
    //     Return the String that is the concatenation of s and "Infinity".
    if (!std::isfinite(valueNumber)) {
        if (valueNumber < 0) {
            return builtins_common::GetTaggedString(thread, "-Infinity");
        }
        return builtins_common::GetTaggedString(thread, "Infinity");
    }
    return NumberHelper::DoubleToString(thread, valueNumber, static_cast<int>(radix));
}

// 20.1.3.7
JSTaggedValue number::proto::ValueOf(EcmaRuntimeCallInfo *argv)
{
    ASSERT(argv);
    BUILTINS_API_TRACE(argv->GetThread(), NumberPrototype, ValueOf);
    // 1. Let x be ? thisNumberValue(this value).
    JSTaggedValue x = ThisNumberValue(argv);
    JSThread *thread = argv->GetThread();
    RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
    return x;
}

JSTaggedNumber ThisNumberValue(EcmaRuntimeCallInfo *argv)
{
    BUILTINS_API_TRACE(argv->GetThread(), Number, ThisNumberValue);
    JSHandle<JSTaggedValue> value = builtins_common::GetThis(argv);
    if (value->IsNumber()) {
        return JSTaggedNumber(value.GetTaggedValue());
    }
    if (value->IsJSPrimitiveRef()) {
        JSTaggedValue primitive = JSPrimitiveRef::Cast(value->GetTaggedObject())->GetValue();
        if (primitive.IsNumber()) {
            return JSTaggedNumber(primitive);
        }
    }
    THROW_TYPE_ERROR_AND_RETURN(argv->GetThread(), "not number type", JSTaggedNumber::Exception());
}
}  // namespace ark::ecmascript::builtins
